package cn.golxen.blog.service.impl;

import cn.golxen.blog.entity.Category;
import cn.golxen.blog.exception.exceptionClass.AddCategoryException;
import cn.golxen.blog.exception.exceptionClass.DeleteCategoryException;
import cn.golxen.blog.mapper.CategoryMapper;
import cn.golxen.blog.mapper.EssayMapper;
import cn.golxen.blog.rabbitMQ.producer.Producer;
import cn.golxen.blog.redis.CategoryRedis;
import cn.golxen.blog.redis.EssayRedis;
import cn.golxen.blog.redis.LabelRedis;
import cn.golxen.blog.service.CategoryService;
import cn.golxen.blog.service.EssayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    @Qualifier(value = "taskExecutor")
    ThreadPoolTaskExecutor poolTaskExecutor;

    @Autowired
    EssayRedis rEssay;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    CategoryRedis rCategory;

    @Autowired
    LabelRedis rLabel;

    @Autowired
    Producer producer;

    @Override
    public Integer addCategory(Category category) {
        try {
            Integer integer=categoryMapper.addCategory(category);
            poolTaskExecutor.execute(() -> {
                rCategory.deleteCategory();
            });
            return integer;
        }catch (Exception e){
            e.printStackTrace();
            throw new AddCategoryException();
        }
    }

    @Override
    public List<String> getCategories() {
        return rCategory.getCategories();
    }

    @Override
    public Integer deleteCategory(String category) {
        Integer integer;
//        EssayService essayService = new EssayServiceImpl();
        if (rEssay.getCountOfCategory(category)==0) {
            integer = categoryMapper.deleteCategory(category);

            poolTaskExecutor.execute(() -> {
                rCategory.deleteCategory();
                rLabel.deleteLabelSet(category);
            });
        }else
            throw new DeleteCategoryException();
        return integer;
    }

    @Override
    public Integer getCount() {
        return rCategory.getCount();
    }
}
